/**
 * Copyright (c) 2011-2016, Eason Pan(pylxyhome@vip.qq.com).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jcbase.controller.sys;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections4.CollectionUtils;

import com.jcbase.core.auth.anno.RequiresPermissions;
import com.jcbase.core.auth.interceptor.SysLogInterceptor;
import com.jcbase.core.controller.JCBaseController;
import com.jcbase.core.pojo.ObjDetail;
import com.jcbase.core.util.IWebUtils;
import com.jcbase.core.view.InvokeResult;
import com.jcbase.model.SysConfig;
import com.jcbase.model.SysObj;
import com.jcbase.model.SysObjShare;
import com.jcbase.model.SysRole;
import com.jcbase.model.SysSite;
import com.jcbase.model.SysUser;
import com.jcbase.model.SysUserRole;
import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

/**
 * 系统对象管理
 * 
 * @author eason
 */

public class ObjShareController extends JCBaseController
{

	@RequiresPermissions(value = { "/sys/objShare" })
	public void index()
	{
		render("obj_index.jsp");
	}

	@RequiresPermissions(value = { "/sys/objShare" })
	public void getShareObjMeView()
	{
		render("obj_share_me.jsp");
	}

	@RequiresPermissions(value = { "/sys/objShare" })
	public void getShareObjOtherView()
	{
		render("obj_share_other.jsp");
	}

	@RequiresPermissions(value = { "/sys/objShare" })
	public void shareOther()
	{
		String ids = this.getPara("ids");
		setAttr("ids", ids);
		render("obj_add_share.jsp");
	}

	@RequiresPermissions(value = { "/sys/objShare" })
	public void getCheckShareObjView()
	{
		render("obj_share_check.jsp");
	}

	@RequiresPermissions(value = { "/sys/objShare" })
	public void getListData()
	{
		int totalRow;
		int totalPage;

		StringBuilder sqlSel = new StringBuilder();
		StringBuilder sqlCount = new StringBuilder();
		StringBuilder sql = new StringBuilder();
		SysUser user = IWebUtils.getCurrentSysUser(getRequest());
		List<SysUserRole> list = SysRole.me.getRole(getRequest());
		List<Record> Recordlist = new ArrayList<Record>();
		if (SysRole.me.checkIsAdmin(list))
		{

			sqlSel.append("select so.*,soc.id as collId,soa.id as  shareId, sit.name as siteName ");
			sqlCount.append("select count(*) ");
			sql.append("from sys_obj so ");
			sql.append(" left join sys_obj_colletc soc on(soc.obj_id =so.id and soc.user_id = ");
			sql.append(user.getId() + ")");
			sql.append(" left join sys_obj_share soa on(soa.obj_id =so.id and soa.user_id = ");
			sql.append(user.getId() + ")");
			sql.append(" left join sys_site sit on sit.id = so.site_id");

			Recordlist = Db.find(sqlSel.append(sql.toString()).toString());
			List<Record> RecordCount = Db.find(sqlCount.append(sql.toString()).toString());

			totalRow = RecordCount.size();
			if (totalRow == 0)
			{
				totalPage = 1;
			}
			else
			{
				totalPage = totalRow / this.getRows() + 1;
			}
		}
		else
		{
			// 查找满足自己角色的对象
			sqlSel.append("select so.*,soc.id as collId,soa.id as  shareId, sit.name as siteName ");
			sqlCount.append("select count(*) ");
			sql.append("from sys_obj so ");
			sql.append(" left join sys_obj_colletc soc on(soc.obj_id =so.id and soc.user_id = ");
			sql.append(user.getId() + ")");
			sql.append(" left join sys_obj_share soa on(soa.obj_id =so.id and soa.user_id = ");
			sql.append(user.getId() + ")");
			sql.append(" left join sys_site sit on sit.id = so.site_id");

			sql.append(
					" where so.id in (select obj_id from sys_role_obj where role_id in (select role_id from sys_user_role where user_id =");
			sql.append(user.getId() + "))");
			sql.append(" or user_name = ");
			sql.append("'" + user.getName() + "'");

			Recordlist = Db.find(sqlSel.append(sql.toString()).toString());
			// 查找满足自己创建的对象
			List<Record> RecordCount = Db.find(sqlCount.append(sql.toString()).toString());
			totalRow = RecordCount.size();
			if (totalRow == 0)
			{
				totalPage = 1;
			}
			else
			{
				totalPage = totalRow / this.getRows() + 1;
			}
		}
		List<ObjDetail> Objlist = new ArrayList<ObjDetail>();
		for (Record record : Recordlist)
		{
			ObjDetail objDetail = new ObjDetail();
			if (record.getInt("site_id") != null)
			{
				objDetail.setSiteId(record.getInt("site_id"));
			}
			objDetail.setOwnName(record.getStr("user_name"));
			objDetail.setSiteName(record.getStr("siteName"));
			objDetail.setId(record.getInt("id"));
			objDetail.setName(record.getStr("name"));
			objDetail.setLink(record.getStr("link"));
			objDetail.setParams(record.getStr("params"));
			objDetail.setSubject(record.getStr("subject"));
			if (record.getLong("collId") != null)
			{
				objDetail.setColletc("已收藏");
			}
			else
			{
				objDetail.setColletc("未收藏");
			}
			if (record.getLong("shareId") != null)
			{
				objDetail.setShare("已分享");
			}
			else
			{
				objDetail.setShare("未分享");
			}
			Objlist.add(objDetail);
		}

		Page<ObjDetail> pageInfo = new Page<ObjDetail>(Objlist, this.getPage(), this.getRows(), totalPage, totalRow);
		user = SysUser.me.findById(user.getId());
		List<ObjDetail> ObjDetailList = pageInfo.getList();
		SysConfig host = SysConfig.me.findById(1);
		for (ObjDetail sysObj : ObjDetailList)
		{

			StringBuffer sb = new StringBuffer();
			sb.append("<a href = '#' onclick = \"forword('");
			sb.append(host.getValue());
			sb.append(sysObj.getLink());

			String common = user.getParams();
			if (common != null && !"".equals(common))
			{
				sysObj.setParams(common);
				String params[] = common.split(",");
				for (String param : params)
				{
					sb.append("&");
					sb.append(param);
				}
			}

			sb.append("')\">");
			sb.append(sysObj.getLink());
			sb.append("</a>");
			sysObj.setLink(sb.toString());
		}
		this.renderJson(SysObj.me.toJqGridView(pageInfo, 1));
	}

	@RequiresPermissions(value = { "/sys/objShare" })
	public void getObjBySiteId()
	{
		int totalRow;
		int totalPage;
		String SiteId = this.getPara("siteId");
		StringBuilder sql = new StringBuilder();

		// 获取该节点下所有子节点
		List<SysSite> siteList = SysSite.me.find("select * from sys_site where pid = " + SiteId);
		String ids = "" + SiteId + ",";
		if (CollectionUtils.isNotEmpty(siteList))
		{
			for (SysSite sysSite : siteList)
			{
				ids = ids + sysSite.getId() + ",";
			}
		}

		ids = ids.substring(0, ids.length() - 1);
		// 查询总数
		sql.append(" select Count(*) ");
		sql.append("from sys_obj so");
		sql.append(" left join sys_site st on st.id = so.site_id ");
		sql.append(" where so.site_id in (");
		sql.append(ids + ")");
		totalRow = Db.find(sql.toString()).size();
		// 查询对象
		sql = new StringBuilder();

		sql.append(" select so.*,st.id as siteId,st.name as siteName ");
		sql.append("from sys_obj so");
		sql.append(" left join sys_site st on st.id = so.site_id ");
		sql.append(" where so.site_id in (");
		sql.append(ids + ")");
		List<Record> ObjList = Db.find(sql.toString());
		List<ObjDetail> list = new ArrayList<ObjDetail>();
		for (Record record : ObjList)
		{
			ObjDetail objDetail = new ObjDetail();
			objDetail.setSiteId(record.getInt("siteId"));
			objDetail.setSiteName(record.getStr("siteName"));
			objDetail.setId(record.getInt("id"));
			objDetail.setName(record.getStr("name"));
			objDetail.setLink(record.getStr("link"));
			objDetail.setParams(record.getStr("params"));
			objDetail.setSubject(record.getStr("subject"));
			list.add(objDetail);
		}

		if (totalRow == 0)
		{
			totalPage = 1;
		}
		else
		{
			totalPage = totalRow / this.getRows() + 1;
		}

		Page<ObjDetail> pageInfo = new Page<ObjDetail>(list, this.getPage(), this.getRows(), totalPage, totalRow);

		List<ObjDetail> objList = pageInfo.getList();
		SysUser user = IWebUtils.getCurrentSysUser(getRequest());
		SysConfig host = SysConfig.me.findById(1);
		for (ObjDetail sysObj : objList)
		{

			StringBuffer sb = new StringBuffer();
			sb.append("<a href = '#' onclick = \"forword('");
			sb.append(host.getValue());
			sb.append(sysObj.getLink());

			String common = user.getParams();
			if (common != null && !"".equals(common))
			{
				sysObj.setParams(common);
				String params[] = common.split(",");
				for (String param : params)
				{
					sb.append("&");
					sb.append(param);
				}
			}

			sb.append("')\">");
			sb.append(sysObj.getLink());
			sb.append("</a>");
			sysObj.setLink(sb.toString());
		}
		this.renderJson(SysObj.me.toJqGridView(pageInfo, 1));
	}

	// 获取别人共享给我的对象
	@Before(SysLogInterceptor.class)
	@RequiresPermissions(value = { "/sys/objShare" })
	public void getShareMeObjList()
	{
		int totalRow = 0;
		int totalPage = 0;
		SysUser user = IWebUtils.getCurrentSysUser(getRequest());
		StringBuilder sqlSel = new StringBuilder();
		StringBuilder sqlCount = new StringBuilder();
		StringBuilder sql = new StringBuilder();
		List<Record> Recordlist = new ArrayList<Record>();
		sqlSel.append(
				"select so.*,soa.id as shareInfoId,soa.type as shareStatus,su.name as beShareName,su2.name as shareUserName");

		sqlCount.append("select count(*) ");

		sql.append(" from sys_obj_share  soa ");
		sql.append(" left join sys_obj so on soa.obj_id =so.id ");
		sql.append(" left join sys_user su  on su.id = soa.user_id ");
		sql.append(" left join sys_user su2  on su2.id = soa.share_user_id ");

		sql.append("where soa.type = 0 and soa.user_id = ");

		sql.append(user.getId());
		Recordlist = Db.find(sqlSel.append(sql.toString()).toString());
		List<Record> RecordCount = Db.find(sqlCount.append(sql.toString()).toString());
		totalRow = RecordCount.size();
		if (totalRow == 0)
		{
			totalPage = 1;
		}
		else
		{
			totalPage = totalRow / this.getRows() + 1;
		}
		List<ObjDetail> Objlist = new ArrayList<ObjDetail>();
		for (Record record : Recordlist)
		{
			ObjDetail objDetail = new ObjDetail();
			objDetail.setId(record.getInt("id"));
			objDetail.setShareInfoId(record.getLong("shareInfoId"));
			objDetail.setName(record.getStr("name"));
			objDetail.setOwnName(record.getStr("user_name"));
			objDetail.setLink(record.getStr("link"));
			objDetail.setParams(record.getStr("params"));
			objDetail.setSubject(record.getStr("subject"));
			objDetail.setUserName(record.getStr("shareUserName"));
			objDetail.setShareName(record.getStr("beShareName"));
			Integer type = record.getInt("shareStatus");
			if (type != null)
			{
				if (type == 2)
				{
					objDetail.setStatus("审核中");
				}
				else
				{
					objDetail.setStatus("分享中");
				}
			}
			objDetail.setSubject(record.getStr("subject"));
			Objlist.add(objDetail);
		}
		Page<ObjDetail> pageInfo = new Page<ObjDetail>(Objlist, this.getPage(), this.getRows(), totalPage, totalRow);

		user = SysUser.me.findById(user.getId());
		List<ObjDetail> objList = pageInfo.getList();
		SysConfig host = SysConfig.me.findById(1);
		for (ObjDetail sysObj : objList)
		{
			StringBuffer sb = new StringBuffer();
			sb.append("<a href = '#' onclick = \"forword('");
			sb.append(host.getValue());
			sb.append(sysObj.getLink());

			String common = user.getParams();
			if (common != null && !"".equals(common))
			{
				sysObj.setParams(common);
				String params[] = common.split(",");
				for (String param : params)
				{
					sb.append("&");
					sb.append(param);
				}
			}

			sb.append("')\">");
			sb.append(sysObj.getLink());
			sb.append("</a>");
			sysObj.setLink(sb.toString());
		}
		this.renderJson(SysObj.me.toJqGridView(pageInfo, 1));
	}

	// 获取我共享给别人的对象
	@Before(SysLogInterceptor.class)
	@RequiresPermissions(value = { "/sys/objShare" })
	public void getShareOtherObjList()
	{
		int totalRow = 0;
		int totalPage = 0;
		SysUser user = IWebUtils.getCurrentSysUser(getRequest());
		StringBuilder sqlSel = new StringBuilder();
		StringBuilder sqlCount = new StringBuilder();
		StringBuilder sql = new StringBuilder();
		List<Record> Recordlist = new ArrayList<Record>();
		// 我分享给别人的 包括审核中和审核成功的
		sqlSel.append(
				"select so.*,soa.id as shareInfoId,soa.type as shareStatus,su.name as beShareName,su2.name as shareUserName");
		sqlCount.append("select count(*) ");
		sql.append(" from sys_obj_share soa  ");
		sql.append(" left join sys_obj so on soa.obj_id =so.id ");
		sql.append(" left join sys_user su  on su.id = soa.user_id ");
		sql.append(" left join sys_user su2  on su2.id = soa.share_user_id ");
		sql.append("where share_user_id = ");
		sql.append(user.getId());
		Recordlist = Db.find(sqlSel.append(sql.toString()).toString());
		List<Record> RecordCount = Db.find(sqlCount.append(sql.toString()).toString());
		totalRow = RecordCount.size();
		if (totalRow == 0)
		{
			totalPage = 1;
		}
		else
		{
			totalPage = totalRow / this.getRows() + 1;
		}
		List<ObjDetail> Objlist = new ArrayList<ObjDetail>();
		for (Record record : Recordlist)
		{
			ObjDetail objDetail = new ObjDetail();
			objDetail.setId(record.getInt("id"));
			objDetail.setShareInfoId(record.getLong("shareInfoId"));
			objDetail.setName(record.getStr("name"));
			objDetail.setLink(record.getStr("link"));
			objDetail.setOwnName(record.getStr("user_name"));
			objDetail.setParams(record.getStr("params"));
			objDetail.setSubject(record.getStr("subject"));
			objDetail.setUserName(record.getStr("shareUserName"));
			objDetail.setShareName(record.getStr("beShareName"));
			Integer type = record.getInt("shareStatus");
			if (type != null)
			{
				if (type == 2)
				{
					objDetail.setStatus("审核中");
				}
				else
				{
					objDetail.setStatus("分享中");
				}
			}
			objDetail.setSubject(record.getStr("subject"));
			Objlist.add(objDetail);
		}
		Page<ObjDetail> pageInfo = new Page<ObjDetail>(Objlist, this.getPage(), this.getRows(), totalPage, totalRow);

		pageInfo = changeBean(pageInfo, user);

		this.renderJson(SysObj.me.toJqGridView(pageInfo, 1));
	}

	// 取消共享
	@RequiresPermissions(value = { "/sys/objShare" })
	public void deleteShareOtherObj()
	{
		// 我分享给别人的 包括审核中和审核成功的
		String id = this.getPara("ids");
		SysObjShare.me.deleteShare(id);
		this.renderJson(InvokeResult.success());

	}

	public Page<ObjDetail> changeBean(Page<ObjDetail> pageInfo, SysUser user)
	{

		List<ObjDetail> objList = pageInfo.getList();
		SysConfig host = SysConfig.me.findById(1);
		for (ObjDetail sysObj : objList)
		{
			StringBuffer sb = new StringBuffer();
			sb.append("<a href = '#' onclick = \"forword('");
			sb.append(host.getValue());
			sb.append(sysObj.getLink());

			String common = user.getParams();
			if (common != null && !"".equals(common))
			{
				sysObj.setParams(common);
				String params[] = common.split(",");
				for (String param : params)
				{
					sb.append("&");
					sb.append(param);
				}
			}

			sb.append("')\">");
			sb.append(sysObj.getLink());
			sb.append("</a>");
			sysObj.setLink(sb.toString());
		}
		return pageInfo;
	}

	@RequiresPermissions(value = { "/sys/obj" })
	public void objAddShareSave()
	{
		String[] otherUserId = this.getParaValues("otherUserId[]");
		String ids = this.getPara("ids");
		SysUser user = IWebUtils.getCurrentSysUser(getRequest());
		// 查询是否
		boolean result = SysObjShare.me.insertShareObj(user, ids, otherUserId);
		this.renderJson(InvokeResult.success(result));
	}

	// 分享对象审核
	@Before(SysLogInterceptor.class)
	@RequiresPermissions(value = { "/sys/objShare" })
	public void shareObjCheck()
	{
		// 审核状态
		int status = this.getParaToInt("status");
		// 分享的消息Id
		String ids = this.getPara("ids");
		// update
		SysObjShare.me.checkShareObj(status, ids);
		this.renderJson(InvokeResult.success());
	}

	// 获取需要批准分享对象
	@RequiresPermissions(value = { "/sys/objShare" })
	public void getCheckShareObjList()
	{
		int totalRow = 0;
		int totalPage = 0;
		SysUser user = IWebUtils.getCurrentSysUser(getRequest());
		List<SysUserRole> list = SysRole.me.getRole(getRequest());

		StringBuilder sqlSel = new StringBuilder();
		StringBuilder sqlCount = new StringBuilder();
		StringBuilder sql = new StringBuilder();
		List<Record> Recordlist = new ArrayList<Record>();

		sqlSel.append(
				"select so.*,soa.id as shareInfoId,soa.type as shareStatus,su.name as beShareName,su2.name as shareUserName");
		sqlCount.append("select count(*) ");
		sql.append(" from sys_obj_share soa  ");
		sql.append(" left join sys_obj so on soa.obj_id =so.id ");
		sql.append(" left join sys_user su  on su.id = soa.user_id ");
		sql.append(" left join sys_user su2  on su2.id = soa.share_user_id ");
		if (SysRole.me.checkIsAdmin(list))
		{
			sql.append("where soa.type = 2");
		}
		else
		{
			sql.append("where so.site_id in ");
			sql.append("(" + user.getSiteId() + ")");
			sql.append("and soa.type = 2");
		}

		Recordlist = Db.find(sqlSel.append(sql.toString()).toString());
		List<Record> RecordCount = Db.find(sqlCount.append(sql.toString()).toString());
		totalRow = RecordCount.size();
		if (totalRow == 0)
		{
			totalPage = 1;
		}
		else
		{
			totalPage = totalRow / this.getRows() + 1;
		}
		List<ObjDetail> Objlist = new ArrayList<ObjDetail>();
		for (Record record : Recordlist)
		{
			ObjDetail objDetail = new ObjDetail();
			if (record.getInt("id") == null)
			{
				continue;
			}
			else
			{
				objDetail.setId(record.getInt("id"));
				objDetail.setShareInfoId(record.getLong("shareInfoId"));
				objDetail.setName(record.getStr("name"));
				objDetail.setLink(record.getStr("link"));
				objDetail.setParams(record.getStr("params"));
				objDetail.setSubject(record.getStr("subject"));
				objDetail.setUserName(record.getStr("shareUserName"));
				objDetail.setShareName(record.getStr("beShareName"));
				Integer type = record.getInt("shareStatus");
				if (type != null)
				{
					if (type == 2)
					{
						objDetail.setStatus("审核中");
					}
					else
					{
						objDetail.setStatus("分享中");
					}
				}
				objDetail.setSubject(record.getStr("subject"));
				Objlist.add(objDetail);
			}
		}
		Page<ObjDetail> pageInfo = new Page<ObjDetail>(Objlist, this.getPage(), this.getRows(), totalPage, totalRow);

		user = SysUser.me.findById(user.getId());
		List<ObjDetail> objList = pageInfo.getList();
		SysConfig host = SysConfig.me.findById(1);
		for (ObjDetail sysObj : objList)
		{
			StringBuffer sb = new StringBuffer();
			sb.append("<a href = '#' onclick = \"forword('");
			sb.append(host.getValue());
			sb.append(sysObj.getLink());

			String common = user.getParams();
			if (common != null && !"".equals(common))
			{
				sysObj.setParams(common);
				String params[] = common.split(",");
				for (String param : params)
				{
					sb.append("&");
					sb.append(param);
				}
			}

			sb.append("')\">");
			sb.append(sysObj.getLink());
			sb.append("</a>");
			sysObj.setLink(sb.toString());
		}
		this.renderJson(SysObj.me.toJqGridView(pageInfo, 1));
	}

}
